from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import random  # 随机等待

def random_sleep(t: float=0.0):
    """
    随机等待 t 秒到 t+1 秒。

    参数:
    t (float): 最小等待时间
    """
    time.sleep(t + random.random())


def select_bind_button(driver: WebDriver, button_name: str="全部"):
    """
    根据输入的按钮名称 点击是否绑定wegame/taptap相应的按钮。

    参数:
    driver: Selenium WebDriver对象
    button_name (str): 可选值为 "全部", "是", "否"
    """
    allowed_buttons = ["全部", "是", "否"]
    if button_name not in allowed_buttons:
        raise ValueError(f"Bind WeGame/TapTap: 无效的按钮名称={button_name}")

    button = driver.find_element(By.XPATH, f"//div[text()='{button_name}']")
    button.click()  # 点击找到的按钮
    print(f"Bind WeGame/TapTap: 成功点击 '{button_name}' 按钮.")


def select_system_button(driver: WebDriver, button_name: str = "官服"):
    """
    根据输入的系统名称 点击相应的系统按钮。

    参数:
    driver: Selenium WebDriver对象
    button_name (str): 可选值为 "官服", "哔哩哔哩", "UID靓号", "小米服", "华为服", "OPPO服", "魅族服", "国际服"
    """
    # 允许的按钮名称
    allowed_buttons = [
        "官服",
        "哔哩哔哩",
        "UID靓号",
        "小米服",
        "华为服",
        "OPPO服",
        "魅族服",
        "国际服",
    ]

    # 检查按钮名称是否有效
    if button_name not in allowed_buttons:
        raise ValueError(f"Select System Button: 无效的按钮名称={button_name}")

    # 根据按钮名称选择相应的按钮并点击
    button = driver.find_element(By.XPATH, f"//div[text()='{button_name}']")
    button.click()  # 点击找到的按钮

    # 输出点击结果
    print(f"Select System Button: 成功点击 '{button_name}' 按钮.")


def select_gender_button(driver: WebDriver, button_name: str = "全部"):
    """
    根据输入的性别或全部选择按钮点击相应的按钮。

    参数:
    driver: Selenium WebDriver对象
    button_name (str): 可选值为 "全部", "男主", "女主"
    """
    # 允许的按钮名称
    allowed_buttons = ["全部", "男主", "女主"]

    # 检查按钮名称是否有效
    if button_name not in allowed_buttons:
        raise ValueError(f"Select Gender Button: 无效的按钮名称={button_name}")

    button = driver.find_element(By.XPATH, f"//div[text()='{button_name}']")
    button.click()  # 点击找到的按钮

    # 输出点击结果
    print(f"Select Gender Button: 成功点击 '{button_name}' 按钮.")


def select_account_type_checkbox(driver: WebDriver, account_type: str = ""):
    """

    点击允许的复选框。如果传入具体的account_type，则仅点击该复选框。
    driver: Selenium WebDriver对象
    account_type: 指定的复选框名称。如果为空字符串，则不进行勾选。
    """
    # 允许的复选框名称
    allowed_checkboxes = ["初始号", "顶级账号", "诚心卖"]

    # 如果传入了具体的account_type，则仅点击该复选框
    if account_type != "":
        if account_type in allowed_checkboxes:
            checkboxes = driver.find_elements(By.CSS_SELECTOR, "div.group")
            for checkbox in checkboxes:
                checkbox_text = checkbox.text.strip()
                if checkbox_text == account_type:
                    checkbox.click()
                    print(f"点击了复选框: {checkbox_text}")
        else:
            print(f"复选框名称 '{account_type}' 不在允许的范围内。")
    else:
        print("未指定账号类型, 已跳过勾选。")


def set_price(driver: WebDriver, low: int, high: int):
    """
    driver: Selenium WebDriver对象
    模拟输入价格区间。要求 low 和 high 为合法整数且 low <= high。
    low: 价格下限
    high: 价格上限
    """
    # 检查输入参数的合法性
    if not isinstance(low, int) or not isinstance(high, int):
        raise ValueError("价格下限和上限必须是整数。")

    if low > high:
        raise ValueError("价格下限不能大于上限。")

    # 定位到下限输入框并输入价格
    low_input = driver.find_element(By.CSS_SELECTOR, "input[placeholder='下限']")
    low_input.clear()  # 清空已有内容
    low_input.send_keys(str(low))  # 输入下限价格

    # 定位到上限输入框并输入价格
    high_input = driver.find_element(By.CSS_SELECTOR, "input[placeholder='上限']")
    high_input.clear()  # 清空已有内容
    high_input.send_keys(str(high))  # 输入上限价格

    print(f"已设置价格区间：下限 = {low}, 上限 = {high}")


# def set_character_chain(driver: WebDriver, character_name: str):
#     """
#     选择角色对应的选项，包括触发下拉菜单并点击具体内容。

#     Args:
#         driver (WebDriver): Selenium WebDriver 对象
#         character_name (str): 角色名称
#     """
#     try:
#         # 定位触发下拉菜单的容器图标
#         container_icon = driver.find_element(
#             By.XPATH, "//use[@xlink:href='#icon-rongqi9']"
#         )
#         # 点击图标以展开复选框
#         container_icon.click()
#         print("成功点击容器图标，展开选择菜单")
#     except ConnectionError:
#         print("未找到容器图标，请检查网络连接或页面结构是否发生变化。")

#     try:
#         # 定位复选框中的具体选项
#         option = driver.find_element(By.XPATH, f"//div[text()='{character_name}']")
#         # 点击选项
#         option.click()
#         print(f"成功选择角色：{character_name}")
#     except ConnectionError:
#         print("未找到角色选项，请检查网络连接或页面结构是否发生变化。")


def input_character(driver: WebDriver, character_dict: dict):
    """对角色输入进行模拟，内容为角色和对应的命座
           可以实现自动输入 但无法被触发选择
    Args:
        driver (WebDriver): Selenium WebDriver对象
        character_dict (dict): 角色和命座对应的字典
    """
    # 定位角色名字输入框

    try:
        character_input = driver.find_element(By.CSS_SELECTOR, "input.t-input__inner[placeholder='角色']")
        character_input.send_keys(Keys.ENTER)
    except Exception:
        raise ConnectionError("未找到角色输入框，请检查网络连接或页面结构是否发生变化。")

    for character_name, _ in character_dict.items():
        # 清空已有内容并输入角色名称
        character_input.clear()
        character_input.send_keys(character_name)
        print(f"输入角色名称：{character_name}")

        # 可以在这里等待页面加载结果，确保输入框内容提交后显示匹配的选项
        random_sleep(0)

        # 输入完成后，选择对应的命座
        set_character_chain(driver, character_dict[character_name], character_name)


# def set_character_chain(driver: WebDriver, n: int, character_name: str):
#     """选择角色对应的命座

#     此时应该已经进入了复选框部分。

#     Args:
#         driver (WebDriver): Selenium WebDriver对象
#         n (int): 命座数, n=0, 1, 2, 3, 4, 5, 6
#         character_name (str): 角色名称，用于生成命座名称
#     """
#     # 根据 n 生成命座名称
#     assert n in range(7), "命座数必须在 0 到 6 之间"
#     if n == 0:
#         constellation_name = character_name
#     elif n == 6:
#         constellation_name = f"满命{character_name}"
#     else:
#         constellation_name = f"{n}命{character_name}"
#     a = input("请输入命座选项：")
#     # 定位命座选项，假设命座选项是文本内容
#     try:
#         # 通过命座名称找到对应的命座选项
#         constellation_option = driver.find_element(
#             By.XPATH, f"//div[text()='{constellation_name}']"
#         )
#         constellation_option.click()
#         print(f"已选择命座：{constellation_name}")
#     except Exception as e:
#         print(f"未找到命座：{constellation_name}，跳过该命座")

#     # 添加等待时间以确保点击稳定，避免页面未加载完全
#     random_sleep()


# 记录需要的角色和命座数
character_dict = {
    "椿": 2,
    "今汐": 0,
    
}
# 记录武器及其精炼等级
weapon_dict = {
    "裁春": 0,
    "星序协响": 1,
}


driver = webdriver.Chrome("./chromedriver-win64/chromedriver.exe")
url = "https://www.pxb7.com/buy/10302/1?keyword=&searchType=%E8%87%AA%E7%84%B6%E6%90%9C%E7%B4%A2"
driver.get(url)  # 不需要验证用户就可以查找
driver.maximize_window()
random_sleep()  # 等待网页加载

# 测试按钮
# select_gender_button("女主")
# select_account_type_checkbox("诚心卖")
# set_price(100, 200)
set_character_chain(driver, "椿")


time.sleep(1000)
